/*
 * Serialization.cpp
 *
 */

#include "Serialization.h"
#include <memory.h>

Serializer::Serializer(Binary& data) : data(data) {
	offset = 0;
}

Serializer::~Serializer() {}

void Serializer::serializeString(const String& value) {
	unsigned char size = value.size();
	::memcpy(&data[offset], &size, 1);
	::memcpy(&data[offset + 1], value.data(), size);
	offset += size + 1;
}

void Serializer::setOffset(BigInt value) {
	offset = value;
}

BigInt Serializer::getOffset() const {
	return offset;
}

void Serializer::setOffset(int offset) {
	this->offset = offset;
}

void Serializer::move(BigInt pos) {
	offset = pos;
}

void Serializer::serializeUnsignedLongInt(BigInt value) {
	::memcpy(&data[offset], &value, 4);
	offset += 4;
}

void Serializer::serializeChar(char value) {
	::memcpy(&data[offset], &value, 1);
	offset += 1;
}

Unserializer::Unserializer(const Binary& data) : data(data) {
	offset = 0;
}

Unserializer::~Unserializer() {}

void Unserializer::setOffset(BigInt value) {
	offset = value;
}

BigInt Unserializer::getOffset() const {
	return offset;
}

void Unserializer::setOffset(int offset) {
	this->offset = offset;
}

void Unserializer::move(BigInt pos) {
	offset = pos;
}

BigInt Unserializer::unserializeUnsignedLongInt() {
	BigInt value;
	::memcpy(&value, &data[offset], 4);
	offset += 4;
	return value;
}

String Unserializer::unserializeString() {
	unsigned char size;
	::memcpy(&size, &data[offset], 1);
	String result;
	result.append((const char*)&data[offset + 1], size);
	offset += 1 + size;
	return result;
}

char Unserializer::unserializeChar() {
	char value;
	::memcpy(&value, &data[offset++], 1);
	return value;
}
